package com.umeox.moto.watch.themes.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.widget.ScrollView;


public class AutoScrollView extends ScrollView {
    private int paddingTop = 0;
    private final int MSG_SCROLL = 10;
    private boolean mScrollToBottom;
    private static final int fistTimeScroll = 1500;
    private static final int scrollRate = 150;

    public AutoScrollView(Context context) {
        this(context, null);
    }

    public AutoScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AutoScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    public void startScrolling() {
        mHandler.sendEmptyMessageDelayed(MSG_SCROLL, fistTimeScroll);
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_SCROLL:
                    if (mScrollToBottom) {
                        paddingTop = 0;
                        mHandler.removeCallbacksAndMessages(null);
                        return;
                    }
                    scrollTo(0, paddingTop);
                    paddingTop += 1;
                    mHandler.removeMessages(MSG_SCROLL);
                    mHandler.sendEmptyMessageDelayed(MSG_SCROLL, scrollRate);
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        mScrollToBottom = t + getHeight() >= computeVerticalScrollRange();
    }


}
